package com.zdy.controller;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.zdy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;
import java.util.Map;

/**
 * @Author: Deyou
 * @Date: 2021/4/13
 */

@EnableSwagger2
@RestController
@RequestMapping("/user")
public class UserController {
    /*注入JDBCTemplate*/
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /***
     * 查询所有数据
     * @return
     */
    @GetMapping("/queryAll")
    public String queryAll(){
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from user");
        return maps.toString();
    }

    /***
     * 根据ID 查询用户信息
     * @param id
     * @return
     */
    @GetMapping("/query")
    public String queryById(int id){
        String sql = "select * from user where id = ?";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, id);
        return maps.toString();
    }

    /***
     * 插入一条数据
     * @param user
     * @return
     */
    @PostMapping("/addUser")
    public String addUser(@RequestBody User user){
        String sql = "insert into user(id,name,age) values(?,?,?)";

        jdbcTemplate.update(sql,user.getId(),user.getName(), user.getAge());
        return "插入成功"+ this.queryById(user.getId());
    }

    /***
     * 根据id 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql,id);
        return "删除成功！";
    }

    /***
     * 根据用户id 修改用户名
     * @param id
     * @param name
     * @return
     */
    @PutMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id,String name){
        String sql = "update user set " + "name = ? where id = ?";
        jdbcTemplate.update(sql,name,id);
        return "更新成功，更新后数据为"+this.queryById(id);
    }

}
